package cn.buk.qms.session;

import cn.buk.common.Constant;
import jakarta.servlet.http.HttpSession;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


/**
 *
 * @author yfdai
 * @date 2017/3/24
 */
public class LoginUtil {
    private static final Logger logger = LogManager.getLogger(LoginUtil.class);

    public static void execLoginProcess(AuthenticationManager authenticationManager, HttpSession session, int userId, int entId, String username, String password, String fullName) {
        logger.info("username: {}, password: {}.", username, password);
        
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);

        //调用loadUserByUsername
        Authentication authentication = authenticationManager.authenticate(authRequest);

        SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
        securityContext.setAuthentication(authentication);

        logger.info("{} login.", username);
        SecurityContextHolder.setContext(securityContext);

        // 这个非常重要，否则验证后将无法登陆
        session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
        session.setAttribute(Constant.SESSION_USERID, userId);
        session.setAttribute(Constant.SESSION_USERNAME, username);
        session.setAttribute(Constant.SESSION_FULLNAME, fullName);
        session.setAttribute(Constant.SESSION_LOGINED, 1);
        session.setAttribute(Constant.SESSION_ENTERPRISE_ID, entId);
        session.setAttribute("user_roles", authentication.getAuthorities().toString());
    }
}
